<template>
<!-- 纹理 -->
    <canvas id="canvas"></canvas>
</template>



<script setup lang="ts">
  import {onMounted} from "vue";
  import RenderContext from "@/views/cg/lib/RenderContext.ts";
  import {Model, shape} from "@/views/cg/lib";
  import { Mat4 , multiply4 } from '../lib/matrix'
  import gui from "@/views/cg/lib/gui";
  import GameField from '../game/model/GameField'
  import Game from '../game/Game'

  onMounted(()=>{
    let gl = RenderContext.getGL()

    const game = new Game()

    //  存储所有的单元
    let c=0
    for(let i=0;i<game.field.width;i++){
      for(let j=0; j<game.field.height;j++){
        if(c%20 === 0){
          const unit = game.addUnit(false, i, j)
          unit.setAgent('wander')
        }
        c++
      }
    }
    // 算分辨率 给透视矩阵用的
    const aspect = gl.canvas.width/gl.canvas.height;
    let angle = Math.PI * 0.3;
    // 控制面板
    let controle = {
      light_x:0.0, //
      light_y:0.0, //
      light_z:1, //
      limit:0.95,
      shininess:2,
      u_innerLimit:1.0,
      u_outterLimit:4.0,
    }

    gui.add(controle, 'light_x').min(-5).max(5).step(0.1).name('light_x').onChange((value)=>{})
    gui.add(controle, 'light_y').min(-5).max(5).step(0.1).name('light_y').onChange((value)=>{})
    gui.add(controle, 'light_z').min(-5).max(5).step(0.1).name('light_z').onChange((value)=>{})
    gui.add(controle, 'limit').min(0.9).max(1.0).step(0.01).name('limit').onChange((value)=>{})
    gui.add(controle, 'u_innerLimit').min(1.0).max(2.0).step(0.1).name('u_innerLimit').onChange((value)=>{})
    gui.add(controle, 'u_outterLimit').min(4.0).max(6.0).step(0.1).name('u_outterLimit').onChange((value)=>{})

    function draw() {
      gl.enable(gl.DEPTH_TEST)
      gl.depthFunc(gl.LEQUAL)
      gl.clearDepth(1.0)
      gl.viewport(0.0, 0.0, canvas.width, canvas.height)
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

      // 创建世界坐标
      const mat4 = new Mat4()
      model.setWorldMatrix(mat4
        // 让立方体转起来
        .rotate(0,angle,0)
        .translate(0, 0, -2)
        .getMatrix()
      )

      const camera = [0,0,3]
      model.setMatrixUniform(
        'u_worldview',
        new Mat4()
          .lookAt(...camera,0,0,0)
          .perspective(Math.PI*0.5, aspect, 1.0, 1000)
          .getMatrix()
      )
      // 光源位置
      model.setVectorUniform('u_light', [0, 0, 5])
      // 亮度
      model.setVectorUniform('u_shininess', controle.shininess)
      model.setVectorUniform('u_limit', controle.limit)
      // 光照方向
      model.setVectorUniform('u_lightDirection', [controle.light_x, controle.light_y, controle.light_z])
      model.setVectorUniform('u_innerLimit', controle.u_innerLimit)
      model.setVectorUniform('u_outterLimit', controle.u_outterLimit)

      angle += 0.01
      model.updateMatrix()
      model.draw()
      requestAnimationFrame(draw)
    }
    draw()
  })
</script>

<style scoped lang="scss">
#canvas{
  width: 100%;
  height: 100%;
  display: block;
}
</style>
